﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Model;
using BllFactory;
using IBLL;
using ETWebApi2.Models;
using System.Web;
using System.IO;
using System.Text;

namespace ETWebApi2.Controllers
{
    [JwtAuthActionFilter]
    public class AboutFilesController : ApiController
    {
        private IFiles_tbService m_fileService = ServiceFactory.CreatService<IFiles_tbService>();
        private ICUser_tbService m_cuserService = ServiceFactory.CreatService<ICUser_tbService>();
        private IFileDownLoadLog_tbService m_filedg = ServiceFactory.CreatService<IFileDownLoadLog_tbService>();
        private MyETLockContext m_db = DbContextFactory.GetDbContext();
        /// <summary>
        /// 获取文件详细
        /// </summary>  
        /// <param name="id">文件Id</param>
        /// <returns></returns>
        [Route("details"), HttpGet]
        public HttpResponseMessage Get(int id)
        {
            Files_tb file = m_fileService.GetList(f => f.Id == id).FirstOrDefault();
            var tongji = (from filedown in m_db.FileDownLoadLog_tb
                          join cuser in m_db.CUser_tb
                          on filedown.DUser equals cuser.Id
                          where filedown.FileId == id
                          select new
                          {
                              tongjiName = cuser.UserName
                          }).ToList();
            var names = (from cuser in m_db.CUser_tb
                        join customer in m_db.Customers_tb
                        on cuser.CompanyId equals customer.Id
                        where cuser.Id == file.UploadUserId
                        select new
                        {
                            userName=cuser.UserName,
                            companyName=customer.Name
                        }).ToList();
            string userNames = "";
            string canopenUser = "";
            string[] arr = file.CanOpenUser.Split('|');
            if(arr.Length>0 && !string.IsNullOrEmpty(arr[0]))  //不指定能打开文件的人时  默认所有人都能打开  arr有且只有一个的值是“”
                foreach (var a in arr)
                {
                    userNames += m_cuserService.GetList(c => c.Id == Convert.ToInt32(a)).FirstOrDefault().UserName+",";
                }
            if (userNames.Length < 2)
                canopenUser = "所有员工";
            else
                canopenUser = userNames.Substring(0, userNames.Length - 1);
            string toUsers = "";
            List<FileDownLoadLog_tb> filelg = m_filedg.GetList(f=>f.FileId==id);
            userNames = "";
            if (filelg.Count>0)
                foreach (var item in filelg)
                {
                    userNames+= m_cuserService.GetList(c => c.Id == item.DUser).FirstOrDefault().UserName+",";
                }
            if(userNames.Length>1)
                toUsers = userNames.Substring(0, userNames.Length - 1);
            Detail detail = new Detail()
            {
                FileName = file.Attachment,
                Time = Convert.ToDateTime(file.Time).ToString("yyyy-MM-dd HH:mm:ss"),
                Uploader = names[0].userName,
                CompanyName = names[0].companyName,
                CanOpener = canopenUser,
                ToUser = toUsers,
                DownNum = tongji.Count(),
                FileSize = new BaseClass().ChangeUint((int)file.FileLength)
            };
           return  ObjectToJson.toJson(new {status=200,data= new {total=1,rows=detail } });
        }


        /// <summary>
        /// 文件下载下载 
        /// </summary>   
        /// <param name="fId">需要下载的文件  Id </param>
        //[Route("dowonload"), HttpGet]
        //public HttpResponseMessage DownLoadSingalFile(string token, string fId)
        //{
        //    JwtAuthObject info = new BaseClass().GetInfoByToken(token);
        //    CUser_tb login = m_cuserService.GetList(u => u.Id == info.UserId).FirstOrDefault();
        //    string path = new BaseClass().webConfigPath;//项目根目录 
        //    List<string> pathList = new List<string>();
        //    string firstID = "";
        //    string countID = "";
        //    WriteBug("DownLoadSingalFile", "fId:" + fId);
        //    if (!string.IsNullOrEmpty(fId))
        //    {
        //        string[] fileItem = fId.Split(',');

        //        WriteBug("DownLoadSingalFile", "fileItemCoubt:" + fileItem.Length);
        //        foreach (string s in fileItem)
        //        {
        //            WriteBug("DownLoadSingalFile", "fileItem:" + s);
        //            Files_tb file = m_fileService.GetList(f => f.Id == Convert.ToInt32(s)).FirstOrDefault();
        //            if (file.IsValid == 0 && login.CompanyId == file.CompanyId)
        //                return ObjectToJson.toJson(new { status = 201, error = "文件" + file.Attachment + "已经被禁止下载" });
        //            if (file != null)
        //            {
        //                string rootPath = HttpContext.Current.Server.MapPath("/file");
        //                string pathPath = rootPath + "\\" + Convert.ToDateTime(file.Time).DayOfYear.ToString() + "\\" + file.Id.ToString() + file.Attachment.Substring(file.Attachment.LastIndexOf('.'));//".zip";//
        //                WriteBug("DownLoadSingalFile7", "下载路径:" + pathPath);
        //                if (File.Exists(pathPath))
        //                {
        //                    FileDownLoadLog_tb fdl = m_filedg.GetList(fd => fd.DUser == login.Id && fd.FileId == file.Id).FirstOrDefault();
        //                    if (fdl == null)
        //                    {
        //                        WriteBug("DownLoadSingalFile8", "非接收人下载文件");
        //                        //我不在此文件的下载人列表里，则只有我和发件人是一个公司，或者我属于文件的接收方公司，才可以下载
        //                        pathList.Add(pathPath);
        //                        pathList.Add(file.Attachment);
        //                    }
        //                    else
        //                    {
        //                        if (fdl.FileId == file.Id)//接收人下载文件  fdl  等于null何来比较
        //                        {
        //                            WriteBug("DownLoadSingalFile9", "接收人下载文件");
        //                            if (file.dUserId == 0)//未指定下载人
        //                            {
        //                                if (firstID.Length == 0)
        //                                    firstID = file.Id.ToString();
        //                                else
        //                                    firstID += "," + file.Id.ToString();
        //                            }
        //                            if (countID.Length == 0)
        //                                countID = file.Id.ToString();
        //                            else
        //                                countID += "," + file.Id.ToString();
        //                            pathList.Add(pathPath);
        //                            pathList.Add(file.Attachment);
        //                        }
        //                    }
        //                }
        //                else
        //                    return ObjectToJson.toJson(new { status = 201, error = "文件不存在" + pathPath });
        //            }
        //            else
        //                return ObjectToJson.toJson(new { status = 201, error = "文件不存在" });
        //        }
        //        if (pathList.Count > 0)
        //        {
        //            string zipFile = "";
        //            string name = "";

        //            if (pathList.Count == 2)
        //            {
        //                if (-1 == pathList[0].IndexOf(".zip"))
        //                {
        //                    if (DotNetZip.CompressSingle(login.Id, pathList[0], pathList[1], ref zipFile))//压缩包生成成功
        //                    {
        //                        name = pathList[1].Substring(0, pathList[1].LastIndexOf('.')) + ".zip";
        //                        WriteBug("DownLoadSingalFile10", "压缩包生成成功:" + name);
        //                    }
        //                }
        //                else
        //                {
        //                    zipFile = pathList[0];
        //                    name = pathList[1];
        //                }
        //            }
        //            else
        //            {
        //                if (DotNetZip.CompressMulti(login.Id, pathList, ref zipFile))//压缩包生成成功
        //                {
        //                    string fileName = pathList[1].Substring(0, pathList[1].LastIndexOf('.'));
        //                    name = fileName + "等" + pathList.Count / 2 + "个文件.zip";//存放压缩包全路径  这个临时文件夹可以设定下系统定时清除
        //                }
        //            }
        //            if (name.Length > 4)
        //            {
        //                int nn = 0;
        //                WriteBug("DownLoadSingalFile11", "countID:" + countID.Length + ",firstID" + firstID.Length);
        //                if (countID.Length > 0)
        //                {
        //                    string result = string.Format("UPDATE FileDownLoadLog_tb SET dCount=dCount+1 WHERE DUser={0} and FileId in ({1})", login.Id, countID);
        //                    using (var dbcontext = new MyETLockContext())
        //                    {
        //                        nn = dbcontext.Database.ExecuteSqlCommand(result);
        //                    }
        //                    WriteBug("DownLoadSingalFile11", "修改数据:FileDownLoadLog_tb成功，login.Id：" + login.Id);
        //                }
        //                if (firstID.Length > 0)
        //                {
        //                    if (firstID.Length > 0)
        //                    {
        //                        string sql = string.Format("update Files_tb set dUserId={0},dIP='{1}', dTime='{2}' WHERE Id{3}", login.Id, HttpContext.Current.Request.UserHostAddress, DateTime.Now, " in (" + firstID + ")");
        //                        WriteBug("DownLoadSingalFile11", "修改数据:Files_tb");
        //                        using (var dbcontext = new MyETLockContext())
        //                        {
        //                            nn = dbcontext.Database.ExecuteSqlCommand(sql);

        //                        }
        //                    }
        //                    //更新自己的下载计数,用于评测发送短信的优先级
        //                    if (nn > 0)
        //                    {
        //                        string re = string.Format("UPDATE CUser_tb SET Tag=Tag+1 where Id = {0}", login.Id);
        //                        WriteBug("DownLoadSingalFile11", "修改数据:CUser_tb");
        //                        using (var dbcontext = new MyETLockContext())
        //                        {
        //                            nn = dbcontext.Database.ExecuteSqlCommand(re);
        //                        }
        //                    }
        //                }
        //                DirectCommonDown(zipFile, name); //如果本来就是压缩文件,则直接下载                       
        //            }
        //        }
        //        else
        //            return ObjectToJson.toJson(new { status = 201, error = "文件不存在" });
        //    }
        //    return ObjectToJson.toJson(new { status = 200, rel = true });
        //}


        /// <summary>
        /// 文件下载下载 
        /// </summary>   
        /// <param name="fId">需要下载的文件  Id </param>
        [Route("dowonload"), HttpGet]
        public HttpResponseMessage DownLoadSingalFile1(string token, string fId)
        {
            JwtAuthObject login = new BaseClass().GetInfoByToken(token);
            string path = new BaseClass().webConfigPath;//项目根目录 
            List<string> pathList = new List<string>();
            string firstID = "";
            string countID = "";
            new WriteBug().WriteBugLog("DownLoadSingalFile", "fId:" + fId);
            if (!string.IsNullOrEmpty(fId))
            {
                string[] fileItem = fId.Split(',');
                foreach (string s in fileItem)
                {
                    Files_tb file = m_fileService.GetList(f => f.Id == Convert.ToInt32(s)).FirstOrDefault();
                    string rootPath = HttpContext.Current.Server.MapPath("/file");
                    string pathPath = rootPath + "\\" + Convert.ToDateTime(file.Time).DayOfYear.ToString() + "\\" + file.Id.ToString() + file.Attachment.Substring(file.Attachment.LastIndexOf('.'));//".zip";//
                    new WriteBug().WriteBugLog("DownLoadSingalFile7", "下载路径:" + pathPath);
                    FileDownLoadLog_tb fdl = m_filedg.GetList(fd => fd.DUser == login.UserId && fd.FileId == file.Id).FirstOrDefault();
                    if (fdl == null)
                    {
                        new WriteBug().WriteBugLog("DownLoadSingalFile8", "非接收人下载文件");
                        //我不在此文件的下载人列表里，则只有我和发件人是一个公司，或者我属于文件的接收方公司，才可以下载
                        pathList.Add(pathPath);
                        pathList.Add(file.Attachment);
                    }
                    else
                    {
                        if (fdl.FileId == file.Id)//接收人下载文件  fdl    
                        {
                            new WriteBug().WriteBugLog("DownLoadSingalFile9", "接收人下载文件");
                            if (file.dUserId == 0)//未指定下载人
                            {
                                if (firstID.Length == 0)
                                    firstID = file.Id.ToString();
                                else
                                    firstID += "," + file.Id.ToString();
                            }
                            if (countID.Length == 0)
                                countID = file.Id.ToString();
                            else
                                countID += "," + file.Id.ToString();
                            pathList.Add(pathPath);
                            pathList.Add(file.Attachment);
                        }
                    }
                }
                if (pathList.Count > 0)
                {
                    string zipFile = "";
                    string name = "";
                    if (pathList.Count == 2)//单个文件
                    {
                        name = SingleFile(pathList, login.UserId, ref zipFile);
                    }
                    else //说明有多个文件
                    {
                        if (DotNetZip.CompressMulti(login.UserId, pathList, ref zipFile))//压缩包生成成功
                        {
                            string fileName = pathList[1].Substring(0, pathList[1].LastIndexOf('.'));
                            name = fileName + "等" + pathList.Count / 2 + "个文件.zip";//存放压缩包全路径  这个临时文件夹可以设定下系统定时清除
                        }
                    }
                    if (name.Length > 4)
                    {
                        //更新数据
                        UpdateData(countID, firstID, login.UserId);
                        DirectCommonDown(zipFile, name); //如果本来就是压缩文件,则直接下载                       
                    }
                }
                else
                    return ObjectToJson.toJson(new { status = 201, error = "文件不存在" });
            }
            return ObjectToJson.toJson(new { status = 200, rel = true });
        }

        /// <summary>
        /// 单个文件下载
        /// </summary>
        /// <param name="pathList">文件路径以及名称</param>
        /// <param name="Id">登陆者Id</param>
        /// <param name="zipFile"></param>
        /// <returns></returns>
        private string SingleFile(List<string> pathList,int Id,ref string zipFile)
        {
            string name = "";
            if (-1 == pathList[0].IndexOf(".zip"))
            {
                if (DotNetZip.CompressSingle(Id, pathList[0], pathList[1], ref zipFile))//压缩包生成成功
                {
                    name = pathList[1].Substring(0, pathList[1].LastIndexOf('.')) + ".zip";
                    new WriteBug().WriteBugLog("DownLoadSingalFile10", "压缩包生成成功:" + name);
                }
            }
            else
            {
                zipFile = pathList[0];
                name = pathList[1];
            }
            return name;
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="countID">下载的文件ID</param>
        /// <param name="firstID">未指定下载人时的文件ID</param>
        /// <param name="Id">当前登陆ID</param>
        /// <returns></returns>
        private void UpdateData(string countID, string firstID,int Id )
        {
            int nn = 0;
            try
            {
                if (countID.Length > 0)
                {
                    string result = string.Format("UPDATE FileDownLoadLog_tb SET dCount=dCount+1 WHERE DUser={0} and FileId in ({1})", Id, countID);
                    using (var dbcontext = new MyETLockContext())
                    {
                        nn = dbcontext.Database.ExecuteSqlCommand(result);
                    }
                }
                if (firstID.Length > 0)
                {
                    if (firstID.Length > 0)
                    {
                        string sql = string.Format("update Files_tb set dUserId={0},dIP='{1}', dTime='{2}' WHERE Id{3}", Id, HttpContext.Current.Request.UserHostAddress, DateTime.Now, " in (" + firstID + ")");
                        using (var dbcontext = new MyETLockContext())
                        {
                            nn = dbcontext.Database.ExecuteSqlCommand(sql);

                        }
                    }
                    //更新自己的下载计数,用于评测发送短信的优先级 
                    if (nn > 0)
                    {
                        string re = string.Format("UPDATE CUser_tb SET Tag=Tag+1 where Id = {0}", Id);
                        using (var dbcontext = new MyETLockContext())
                        {
                            nn = dbcontext.Database.ExecuteSqlCommand(re);
                        }
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
            
        }
        /// <summary>
        /// 判断下载文件是否存在 
        /// </summary>
        /// <param name="fileItem"></param>
        /// <param name="login"></param>
        /// <returns></returns>
        [HttpGet,Route("isfile")]
        public HttpResponseMessage IsExistFile(string fid,string token)
        {
            JwtAuthObject login = new BaseClass().GetInfoByToken(token);
            if (!fid.Equals(""))
            {
                string[] fileItem = fid.Split(',');
                foreach (string s in fileItem)
                {
                    Files_tb file = m_fileService.GetList(f => f.Id == Convert.ToInt32(s)).FirstOrDefault();
                    if (file.IsValid == 0 && login.CurentCopmpanyId == file.CompanyId)
                        return ObjectToJson.toJson(new { status = 201, error = "文件" + file.Attachment + "已经被禁止下载" });
                    if (file != null)
                    {
                        string rootPath = HttpContext.Current.Server.MapPath("/file");
                        string pathPath = rootPath + "\\" + Convert.ToDateTime(file.Time).DayOfYear.ToString() + "\\" + file.Id.ToString() + file.Attachment.Substring(file.Attachment.LastIndexOf('.'));//".zip";//
                        new WriteBug().WriteBugLog("DownLoadSingalFile7", "下载路径:" + pathPath);
                        if (!File.Exists(pathPath))
                            return ObjectToJson.toJson(new { status = 201, error = "文件" + file.Attachment + "不存在" });//文件夹中没有该文件
                    }
                    else
                        return ObjectToJson.toJson(new { status = 201, error = "文件" + file.Attachment + "记录不存在" });//数据库中没有相关记录
                }
            }else
                return ObjectToJson.toJson(new { status = 201, error = "下载参数出错" });
            return ObjectToJson.toJson(new { status = 200, rel = true });
        }

        //pathname是真实全路径名， fileName是表象文件名 
        private void DirectCommonDown(string pathname, string downloadName)
        {
            FileInfo DownloadFile = new FileInfo(pathname);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.Buffer = false;
            HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(downloadName, Encoding.UTF8));
            HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
            HttpContext.Current.Response.WriteFile(pathname);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }



        //批量下载 打包要下载的文件生成zip  暂时只在我的文件里面提供 
        [Route("zipdown"), HttpGet]
        public HttpResponseMessage ZipDownLoad(string fileItems)
        {
            JwtAuthObject info = new BaseClass().GetInfoByToken(Request.Headers.Authorization.Parameter);
            CUser_tb user = m_cuserService.GetList(u => u.Id == info.UserId).FirstOrDefault();
            string[] fileItem =fileItems.ToString().Split(',');
            List<string> pathList = new List<string>();
            string inID = "";
            foreach (string s in fileItem)
            {
                Files_tb file = m_fileService.GetList(f=>f.Id==int.Parse(s)).FirstOrDefault();
                if (file != null)
                {
                    string rootPath = HttpContext.Current.Server.MapPath("/file");
                    string pathPath = rootPath + "\\" +Convert.ToDateTime(file.Time).DayOfYear.ToString() + "\\" + file.Id.ToString() + file.Attachment.Substring(file.Attachment.LastIndexOf('.'));//".zip";//

                    if (File.Exists(pathPath))
                    {
                        if (file.dUserId == 0)
                        {
                            if (inID.Length == 0)
                                inID = file.Id.ToString();
                            else
                                inID += "," + file.Id.ToString();
                        }

                        pathList.Add(pathPath);
                        pathList.Add(file.Attachment);
                    }
                    else
                    {
                       return ObjectToJson.toJson(new { status = 201, error = "文件不存在"+ file.Attachment });                        
                    }
                }
                else
                {
                   return ObjectToJson.toJson(new { status = 201, error = "文件不存在"  });
                }
            }
            string pathName = "";//压缩包的全路径
            if (DotNetZip.CompressMulti(user.Id, pathList, ref pathName))//压缩包生成成功
            {
                string name = pathList[1].Substring(0, pathList[1].LastIndexOf('.'));
                string fileName = name + "等" + pathList.Count / 2 + "个文件.zip";//存放压缩包全路径  这个临时文件夹可以设定下系统定时清除
                if (inID.Length > 0)
                {
                    //int up = fileBLL.UpdateDownDate(user.Id, HttpContext.Current.Request.UserHostAddress, " in (" + inID + ")");
                    List<Files_tb> files = m_fileService.GetList(f=>inID.Split(',').Contains(f.Id.ToString()));
                    for (int i = 0; i < files.Count; i++)
                    {
                        files[i].dUserId = user.Id;
                        files[i].dTime = DateTime.Now;
                        files[i].IP = HttpContext.Current.Request.UserHostAddress;
                        m_fileService.Update(files[i]);
                    }
                }
                //HttpContext.Current.Response.Write(string.Format("OK&CommonDownload.aspx?pathName={0}&name={1}", HttpContext.Current.Server.UrlEncode(pathName), HttpContext.Current.Server.UrlEncode(fileName)));
               return  ObjectToJson.toJson(new { status = 200,rel=true});
            }
            else
            {
               return  ObjectToJson.toJson(new { status = 201, error = pathName });
            }
        }

    }
}
